﻿namespace WebPacker.Packs.Resources
{
	using System;
	using System.IO;
	using System.Text;
	using WebPacker.Helpers;

	public sealed class FileResource : IResource
	{
		public FileResource(string fileName)
			: this(fileName, Encoding.UTF8)
		{
		}

		public FileResource(string fileName, Encoding encoding)
		{
			if (fileName == null)
			{
				throw new ArgumentNullException("fileName");
			}

			if (encoding == null)
			{
				throw new ArgumentNullException("encoding");
			}

			CheckInvalidPathChars(fileName);

			Name = VirtualPathHelper.NormalizePath(fileName);
			Encoding = encoding;
		}

		public string Name
		{
			get;
			private set;
		}

		public Encoding Encoding { get; set; }
		
		public string GetContent()
		{
			return File.ReadAllText(Name, Encoding);
		}

		public DateTime GetLastModifiedTime()
		{
			return File.GetLastWriteTime(Name);
		}

		private static void CheckInvalidPathChars(string path)
		{
			for (int i = 0; i < path.Length; i++)
			{
				int symbol = path[i];

				// < > | * ? system
				if (symbol == 0x22 || symbol == 0x3c || symbol == 0x3e || symbol == 0x7c || symbol < 0x20 || symbol == 0x2a || symbol == 0x3f)
				{
					throw new ArgumentException(string.Format("File name \"{0}\" is invalid.", path));
				}
			}
		}
	}
}
